﻿using WebApp.BLL.Base;
using WebApp.Common.Caching;
using WebApp.DAL;
using WebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace WebApp.BLL.Manage
{
    /// <summary>
    /// 系统参数
    /// </summary>
    public class S_environmentService : BaseService<S_environment>
    {
        #region (DAL)Repository
        
        #endregion

        #region 构造

        public S_environmentService() : base(new S_environmentRepository()) { }

        #endregion

        #region Save

        public bool Save(List<S_environment> list, List<int> delIds)
        {
            foreach (var item in list)
            {
                if (item.Id == 0)
                {
                    this.CurrentRepository.Add(item, false);
                }
                else
                {
                    this.CurrentRepository.Update(item, false);
                }
            }

            //删除项目
            foreach (int dtlId in delIds)
            {
                var dItem = this.CurrentRepository.Find(dtlId);
                if (dItem != null)
                    this.CurrentRepository.Delete(dItem, false);
            }

            //提交事物
            this.CurrentRepository.Save();

            return true;
        }

        #endregion

        #region GetValue

        /// <summary>
        /// 根据Key获取系统参数值
        /// </summary>
        /// <param name="paramname"></param>
        /// <param name="custcode"></param>
        /// <returns></returns>
        public string GetValue(string paramname)
        {
            var cachekey = "S_environment";

            var result = new MemoryCacheManager().Get<List<S_environment>>(cachekey, () =>
            {
                return this.CurrentRepository.Entities.ToList();
            });

            //if (string.IsNullOrEmpty(custcode))
            //{
            //    custcode = "-";
            //}

            var T = result;//.Where(p => p.Custcode == custcode);

            var item = T.FirstOrDefault(p => paramname.Equals(p.Parametername, StringComparison.OrdinalIgnoreCase));

            return item == null ? string.Empty : item.Parametervalue;
        }

        public void ClearCache()
        {
            var cachekey = "S_environment";

            new MemoryCacheManager().Remove(cachekey);
        }

        #endregion

    }
}
